import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Course',
    component: () => import(/* webpackChunkName: "Learn" */ '@/views/course')
  },
  {
    path: '/courseInfo/:courseId',
    name: 'CourseInfo',
    component: () => import(/* webpackChunkName: "Learn" */ '@/views/course-info'),
    props: true
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "Login" */ '@/views/login')
  },
  {
    path: '/learn',
    name: 'Learn',
    component: () => import(/* webpackChunkName: "Learn" */ '@/views/learn'),
    meta: { requiresAuth: true }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "Learn" */ '@/views/user'),
    meta: { requiresAuth: true }
  },
  {
    path: '/lesson-video/:lessonId',
    name: 'LessonVideo',
    component: () => import(/* webpackChunkName: "Learn" */ '@/views/course-info/video'),
    meta: { requiresAuth: true },
    props: true
  },
  {
    path: '/pay/:courseId',
    name: 'Pay',
    component: () => import(/* webpackChunkName: "pay" */ '@/views/pay'),
    meta: { requiresAuth: true },
    props: true
  },
  {
    path: '*',
    name: 'ErrorPage',
    component: () => import(/* webpackChunkName: "Learn" */ '@/views/errorPage')
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫进行登录检测
router.beforeEach((to, from, next) => {
  // 验证to的路由是否需要身份认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 验证vuex的store中是否存储用户登录信息
    if (!store.state.user) {
      // 未登录，跳转到登录页面
      return next({
        name: 'Login',
        query: {
          redirect: to.fullPath
        }
      })
    }
    next()
  } else {
    next()
  }
})

export default router
